﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RedirectHandler.cs" company="ecblog.codeplex.com">
//   emrecoskun.net - ibrahimatay.com
// </copyright>
// <summary>
//   The redirect handle
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace EcBlog.Routing
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;

    /// <summary>
    /// The redirect handle
    /// </summary>
    public class RedirectHandler : MvcHandler
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RedirectHandler"/> class.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="requestContext"/> parameter is null.</exception>
        public RedirectHandler(RequestContext requestContext)
            : base(requestContext)
        {
        }

        /// <summary>
        /// Called by ASP.NET to begin asynchronous request processing.
        /// </summary>
        /// <param name="httpContext">The HTTP context.</param>
        /// <param name="callback">The asynchronous callback method.</param>
        /// <param name="state">The state of the asynchronous object.</param>
        /// <returns>
        /// The status of the asynchronous call.
        /// </returns>
        protected override IAsyncResult BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, object state)
        {
            if (!httpContext.Request.IsLocal &&
                !httpContext.Request.Url.AbsoluteUri.Contains("://www."))
            {
                httpContext.Response.Status = "301 Moved Permanently";
                httpContext.Response.StatusCode = 301;
                httpContext.Response.AppendHeader("Location", httpContext.Request.Url.AbsoluteUri.Replace("://", "://www."));
            }

             return base.BeginProcessRequest(httpContext, callback, state);
        }
    }
}